//
//  MOCommonUseAddViewController.m
//  MobileOffice
//
//  Created by 冰冰 on 2019/6/7.
//  Copyright © 2019 com.idolmedia. All rights reserved.
//

#import "MOCommonUseAddViewController.h"
#import "MOCommonUseViewCell.h"
#import "MOCommonUseReusableView.h"

@interface MOCommonUseAddViewController ()<UICollectionViewDataSource,UICollectionViewDelegate>

@property(nonatomic,strong)NSMutableArray *dataArray;

@property(nonatomic,strong)NSMutableArray *selectedArray;

@property(nonatomic,strong)UICollectionView *collectionView;

@end

@implementation MOCommonUseAddViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    
    [self setNav];
    
    [self creatView];
    
    [self initData];
    
    [self requestData];
}

-(void)setNav
{
    self.title = @"常用";
    
    self.view.backgroundColor = [UIColor whiteColor];
    
    UIButton *button = [[UIButton alloc]initWithFrame:CGRectMake(10, 0, 38, 38)];
    [button setTitle:@"完成" forState:UIControlStateNormal];
    button.titleLabel.font = FONT_SIZE(14);
    [button setTitleColor:KBlueColor_2C94FF forState:UIControlStateNormal];
    [button addTarget:self action:@selector(clickSureButton) forControlEvents:UIControlEventTouchUpInside];
    [button setContentHorizontalAlignment:(UIControlContentHorizontalAlignmentRight)];
    UIBarButtonItem *rightItem = [[UIBarButtonItem alloc]initWithCustomView:button];
    self.navigationItem.rightBarButtonItem = rightItem;
    
    UIButton *button1 = [[UIButton alloc]initWithFrame:CGRectMake(10, 0, 38, 38)];
    [button1 setTitle:@"取消" forState:UIControlStateNormal];
    button1.titleLabel.font = FONT_SIZE(14);
    [button1 setTitleColor:KBlueColor_2C94FF forState:UIControlStateNormal];
    [button1 addTarget:self action:@selector(clickCancelButton) forControlEvents:UIControlEventTouchUpInside];
    [button1 setContentHorizontalAlignment:(UIControlContentHorizontalAlignmentLeft)];
    UIBarButtonItem *leftItem = [[UIBarButtonItem alloc]initWithCustomView:button1];
    self.navigationItem.leftBarButtonItem = leftItem;
}

-(void)clickCancelButton
{
    [self.navigationController popViewControllerAnimated:YES];
}

-(void)clickSureButton
{
    [self.navigationController popViewControllerAnimated:YES];
}

-(void)creatView
{
    [self.view addSubview:self.collectionView];
}



-(void)initData
{
    self.dataArray = [NSMutableArray array];
    
    self.selectedArray = [NSMutableArray array];
    for (int i = 0; i<self.useDataArray.count; i++) {
        MOCommonUseModel *model = self.useDataArray[i];
        model.typeStr = @"1";
        model.itemIndex = i;
        [self.selectedArray addObject:model];
    }
}


-(void)requestData
{
    NSArray *nameArr = @[@"104",@"105",@"106",@"107"];;
    NSArray *imageArr = @[@"use_daiban",@"use_daibanO",@"use_chaxun",@"use_jiandingwenan"];
    
    NSString *postUrl = [NSString stringWithFormat:@"%@/%@?authorization=%@",FINDALLFAVMENU_URL,[MOUser sharedMOUser].userName,[NSString URLEncodedString:[MOUser sharedMOUser].token]];
    [PPNetworkHelper GET:postUrl parameters:@{} success:^(id responseObject) {
        NSLog(@"获取所有菜单信息:%@",responseObject);
        if ([responseObject isKindOfClass:[NSArray class]]) {
            NSArray *arr = responseObject;
            for (int i = 0; i<arr.count; i++) {
                NSDictionary *dic = arr[i];
                MOCommonUseModel *model = [[MOCommonUseModel alloc]init];
                model.nameStr = [NSString passNullForString:dic[@"menu_name"]];
                model.imageStr = imageArr[[nameArr indexOfObject:arr[i][@"menu_id"]]];
                model.menuId = [NSString passNullForString:dic[@"menu_id"]];
                model.itemIndex = i;
                model.typeStr = @"2";
                [self.dataArray addObject:model];
            }
            [self.collectionView reloadData];
        }
        
    } failure:^(NSError *error) {
        NSLog(@"获取所有菜单信息:%@",[error localizedDescription]);
        [[ADShowMessage shareShowMessage] showTextOnly:[error localizedDescription] showInView:self.view];
    }];
}

#pragma mark -UICollectionViewDataSource,UICollectionViewDelegate
-(NSInteger)numberOfSectionsInCollectionView:(UICollectionView *)collectionView
{
    return 2;
}

-(NSInteger)collectionView:(UICollectionView *)collectionView numberOfItemsInSection:(NSInteger)section{
    
    if (section==0) {
        return self.selectedArray.count;
    }else{
        return self.dataArray.count;
    }

}

- (UICollectionViewCell *)collectionView:(UICollectionView *)collectionView cellForItemAtIndexPath:(NSIndexPath *)indexPath{
    
    MOCommonUseViewCell * cell = [collectionView dequeueReusableCellWithReuseIdentifier:@"cell" forIndexPath:indexPath];
    
    MOCommonUseModel *model;
    if (indexPath.section==0) {
        model = self.selectedArray[indexPath.item];
        model.itemIndex = indexPath.item;
    }else{
        model = self.dataArray[indexPath.item];
        model.itemIndex = indexPath.item;
    }
    
    cell.model = model;
    
    return cell;
    
}

//定义每个UICollectionView 的大小
- (CGSize)collectionView:(UICollectionView *)collectionView layout:(UICollectionViewLayout*)collectionViewLayout sizeForItemAtIndexPath:(NSIndexPath *)indexPath{
    
    return CGSizeMake(SCREEN_WIDTH/3, SCREEN_WIDTH/3);
    
}

-(UIEdgeInsets)collectionView:(UICollectionView *)collectionView layout:(UICollectionViewLayout *)collectionViewLayout insetForSectionAtIndex:(NSInteger)section{
    
    return UIEdgeInsetsMake(0, 0, 0, 0);
    
}

//定义每个UICollectionView 横向的间距
- (CGFloat)collectionView:(UICollectionView *)collectionView layout:(UICollectionViewLayout*)collectionViewLayout minimumInteritemSpacingForSectionAtIndex:(NSInteger)section{
    
    return 0;
}

//定义每个UICollectionView 竖向的间距
- (CGFloat)collectionView:(UICollectionView *)collectionView layout:(UICollectionViewLayout*)collectionViewLayout minimumLineSpacingForSectionAtIndex:(NSInteger)section{
    
    return 0;
}

-(CGSize)collectionView:(UICollectionView *)collectionView layout:(UICollectionViewLayout *)collectionViewLayout referenceSizeForHeaderInSection:(NSInteger)section{
    
    if (section==0) {
        return CGSizeMake(SCREEN_WIDTH,kWConversions(47)+1);
    }else{
        return CGSizeMake(SCREEN_WIDTH,kWConversions(47)+10);
    }
}

//头部显示的内容
- (UICollectionReusableView *)collectionView:(UICollectionView *)collectionView viewForSupplementaryElementOfKind:(NSString *)kind atIndexPath:(NSIndexPath *)indexPath{
    if (kind == UICollectionElementKindSectionHeader) {
        MOCommonUseReusableView *view = [collectionView dequeueReusableSupplementaryViewOfKind:kind withReuseIdentifier:@"headerCell" forIndexPath:indexPath];
        view.section = indexPath.section;
        if (indexPath.section==0) {
            view.backView.y = 1;
            view.titleLabel.text = [NSString stringWithFormat:@"已选菜单(%lu)",(unsigned long)self.selectedArray.count];
        }else{
            view.backView.y = 10;
            view.titleLabel.text = [NSString stringWithFormat:@"更多菜单(%lu)",(unsigned long)self.dataArray.count];
        }
        
        return view;
    }else{
        return nil;
    }
}


- (void)collectionView:(UICollectionView *)collectionView didSelectItemAtIndexPath:(NSIndexPath *)indexPath
{
    if (indexPath.section==0) {//删除
        
        MOCommonUseModel *model = self.selectedArray[indexPath.item];
        NSString *postUrl = [NSString stringWithFormat:@"%@/%@/%@?authorization=%@",DELFAVMENU_URL,model.menuId,[MOUser sharedMOUser].userName,[NSString URLEncodedString:[MOUser sharedMOUser].token]];
        [MBProgressHUD showHUDAddedTo:self.view animated:YES];
        [PPNetworkHelper GET:postUrl parameters:@{} success:^(id responseObject) {
            NSLog(@"删除用户常用菜单:%@",responseObject);
            [MBProgressHUD hideHUDForView:self.view animated:YES];
            if ([responseObject integerValue]==1) {
                model.typeStr = @"2";
                [self.selectedArray removeObjectAtIndex:indexPath.item];
                [self.dataArray addObject:model];
                [self.collectionView reloadData];
                [[NSNotificationCenter defaultCenter]postNotificationName:MENUCHANGESUCESS object:nil];
            }else{
                [[ADShowMessage shareShowMessage] showTextOnly:@"删除失败" showInView:self.view];
            }
        } failure:^(NSError *error) {
            NSLog(@"删除用户常用菜单:%@",[error localizedDescription]);
            [MBProgressHUD hideHUDForView:self.view animated:YES];
            [[ADShowMessage shareShowMessage] showTextOnly:[error localizedDescription] showInView:self.view];
        }];
        
    }else{//添加
        
        MOCommonUseModel *model = self.dataArray[indexPath.item];
        NSString *postUrl = [NSString stringWithFormat:@"%@/%@/%@?authorization=%@",ADDFAVMENU_URL,model.menuId,[MOUser sharedMOUser].userName,[NSString URLEncodedString:[MOUser sharedMOUser].token]];
        [MBProgressHUD showHUDAddedTo:self.view animated:YES];
        [PPNetworkHelper GET:postUrl parameters:@{} success:^(id responseObject) {
            NSLog(@"添加用户常用菜单:%@",responseObject);
            [MBProgressHUD hideHUDForView:self.view animated:YES];
            if ([responseObject[@"flag"] integerValue]==1) {
                model.typeStr = @"1";
                [self.dataArray removeObjectAtIndex:indexPath.item];
                [self.selectedArray addObject:model];
                [self.collectionView reloadData];
                [[NSNotificationCenter defaultCenter]postNotificationName:MENUCHANGESUCESS object:nil];
            }else{
                [[ADShowMessage shareShowMessage] showTextOnly:@"添加失败" showInView:self.view];
            }
        } failure:^(NSError *error) {
            NSLog(@"添加用户常用菜单:%@",[error localizedDescription]);
            [MBProgressHUD hideHUDForView:self.view animated:YES];
            [[ADShowMessage shareShowMessage] showTextOnly:[error localizedDescription] showInView:self.view];
        }];
    }
}


#pragma mark -懒加载
-(UICollectionView *)collectionView
{
    if (!_collectionView) {
        
        UICollectionViewFlowLayout *layout = [[UICollectionViewFlowLayout alloc]init];
        layout.scrollDirection = UICollectionViewScrollDirectionVertical;
        
        _collectionView = [[UICollectionView alloc]initWithFrame:CGRectMake(0,0, SCREEN_WIDTH, SCREEN_HEIGHT-StatusBarAndNavigationBarHeight) collectionViewLayout:layout];
        _collectionView.backgroundColor = [UIColor whiteColor];
        _collectionView.showsVerticalScrollIndicator = NO;
        _collectionView.alwaysBounceVertical = YES;
        _collectionView.delegate = self;
        _collectionView.dataSource = self;
        
        [_collectionView registerClass:[MOCommonUseViewCell class] forCellWithReuseIdentifier:@"cell"];
        [_collectionView registerClass:[MOCommonUseReusableView class] forSupplementaryViewOfKind:UICollectionElementKindSectionHeader withReuseIdentifier:@"headerCell"];
        
    }
    return _collectionView;
}

@end
